#pragma once 

#include <rtc_base/third_party/sigslot/sigslot.h>
#include <rtc_base/socket_address.h>

#include "base/event_loop.h"

namespace xrtc {

class UdpPacketData {
public:
    UdpPacketData(const char* data, size_t size, const rtc::SocketAddress& addr) :
        m_data(new char[size]), m_size(size), m_addr(addr) {
        memcpy(m_data, data, size);
    }
    
    ~UdpPacketData() {
        if (m_data) {
            delete[] m_data;
            m_data = nullptr;
        }
    }

    char* get_data() const { return m_data; }
    size_t get_size() const { return m_size; }
    const rtc::SocketAddress& get_addr() const { return m_addr; }

private:
    char* m_data;
    size_t m_size;
    rtc::SocketAddress m_addr;
};


class AsyncUdpSocket {
public:
    AsyncUdpSocket(EventLoop* ev, int socket);
    ~AsyncUdpSocket();

    // 读取推流端的数据包
    void recv_data();

    // 遍历 m_udp_packet_list 队列，发送UDP数据包
    void send_data();


    // 调用_add_udp_packet()添加UDP数据包到队列中，并开启时间循环
    int send_to(const char* data, size_t size, const rtc::SocketAddress& addr);

    
    sigslot::signal5<AsyncUdpSocket*, char*, size_t, const rtc::SocketAddress&, int64_t> signal_read_packet;

private:
    // 添加UDP数据包
    int _add_udp_packet(const char* data, size_t size, const rtc::SocketAddress& addr);


private:
    EventLoop* m_ev;
    int m_socket;
    IOWatcher* m_socket_watcher;
    char* m_buf;
    size_t m_size;

    std::list<UdpPacketData*> m_udp_packet_list;
};

} // namespace xrtc
